package com.cskt.petproject178.service.third;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.cskt.petproject178.config.AliPayAutoConfigProperties;
import com.cskt.petproject178.mapper.OrderMapper;
import com.cskt.petproject178.pojo.entity.Order;
import com.cskt.petproject178.pojo.exception.BaseException;
import com.cskt.petproject178.pojo.vo.StatusEnum;
import com.cskt.petproject178.util.Constant;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author 27013
 **/

@Service
public class AliPayService {
    private  static  final Logger log=LoggerFactory.getLogger(AliPayService.class);
    @Resource
    private AliPayAutoConfigProperties properties;
    @Resource
    private OrderMapper orderMapper;
    public  String aliPayTrade(String orderNo){
        Order order = orderMapper.selectOrderByOrderNo(orderNo);
        //判断订单状态
        if (ObjectUtils.isEmpty(order)) {
            log.warn("当前订单不存在:orderNo{}",order.getOrderNo());
            throw new BaseException(StatusEnum.ORDER_NOT_EXIST);
        }
        //判断订单状态 必须是待支付 ，以及支付状态必须是未支付
        if (!order.getOrderStatus().equals(Constant.OrderStatus.PENDING_PAYMENT) || !order.getPayStatus().equals(Constant.PayStatus.UNPAID)) {
            log.warn("当前订单状态异常，orderNo:{},orderStatus:{},payStatus:{}",order.getOrderNo(),order.getOrderStatus(),order.getPayStatus());
            throw new BaseException(StatusEnum.ORDER_STATUS_ERROR);
        }
        //调用支付宝支付接口
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setAppId(properties.getAppId());
        alipayConfig.setPrivateKey(properties.getPrivateKey());
        alipayConfig.setAlipayPublicKey(properties.getAlipayPublicKey());
        alipayConfig.setServerUrl(properties.getServiceUrl());
        alipayConfig.setCharset(properties.getCharset());
        alipayConfig.setSignType(properties.getSignType());
        alipayConfig.setFormat(properties.getFormat());
        //准备初始化alipay的client
        try {
            DefaultAlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
            //准备支付订单相关的数据
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.setOutTradeNo(orderNo);
            model.setTotalAmount(order.getTotalMoney().toString());
            model.setSubject("宠爱有家-"+orderNo);

            //FAST_INSTANT_TRADE_PAY 扫码支付
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            //支付页面生成的模式
            model.setQrPayMode("0");
            //准备相关参数
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            //将订单相关的参数封装到请求对象中
            request.setBizModel(model);
            //设置异步回调地址
            request.setNotifyUrl(properties.getNotifyUrl());
            //执行预加载
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
             log.info("支付宝预加载响应结果：{}",response.getBody());
            return response.getBody();
        } catch (AlipayApiException e) {
            log.error("支付宝初始化支付页面异常",e);
            throw new BaseException(StatusEnum.COMMON_EXCEPTION);
        }
    }

    /**
     * @param params    待验签的从支付宝接收到的参数Map
     * @return true：验签通过；false：验签不通过
     * @throws AlipayApiException
     */
    public  void verifyV1(Map<String, String> params){
//异步验签：切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
//公钥证书模式验签，alipayPublicCertPath是支付宝公钥证书引用路径地址，需在对应应用中下载
//boolean signVerified= AlipaySignature.rsaCertCheckV1(params, alipayPublicCertPath, charset,sign_type);
//普通公钥模式验签，切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(params, properties.getAlipayPublicKey(), properties.getCharset(), properties.getSignType());
            //从校验中取出订单号
            Order order = orderMapper.selectOrderByOrderNo(params.get("out_trade_no"));
            //判断订单状态
            if (ObjectUtils.isEmpty(order)) {
                log.warn("当前订单不存在:orderNo{}",order.getOrderNo());
                throw new BaseException(StatusEnum.ORDER_NOT_EXIST);
            }
            //判断订单状态 必须是待支付 ，以及支付状态必须是未支付
            if (!order.getOrderStatus().equals(Constant.OrderStatus.PENDING_PAYMENT) || !order.getPayStatus().equals(Constant.PayStatus.UNPAID)) {
                log.warn("当前订单状态异常，orderNo:{},orderStatus:{},payStatus:{}",order.getOrderNo(),order.getOrderStatus(),order.getPayStatus());
                throw new BaseException(StatusEnum.ORDER_STATUS_ERROR);
            }
            if (signVerified) {
                // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
                //获取支付状态
                String trade_status = params.get("trade_status");
                switch (trade_status) {
                    case "TRADE_SUCCESS"->{
                        //支付成功
                        log.info("支付宝支付成功，订单号：{}",order.getOrderNo());
                        //修改订单状态为已支付
                        order.setPayStatus(Constant.PayStatus.PAYMENT_SUCCESS);
                        order.setPayTime(LocalDateTime.parse(params.get("gmt_payment"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        //修改订单状态为待发货
                        order.setOrderStatus(Constant.OrderStatus.TO_BE_SHIPPED);
                    }
                    case "TRADE_FINISHED"->{
                        //交易结束，不可退款
                        log.info("支付宝交易结束，订单号：{}",order.getOrderNo());
                        //修改订单状态为已完成
                        order.setOrderStatus(Constant.OrderStatus.DONE);
                        order.setPayTime(LocalDateTime.parse(params.get("gmt_payment"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        //修改订单状态为待发货
                        order.setOrderStatus(Constant.OrderStatus.TO_BE_SHIPPED);
                    }
                }
                    orderMapper.updateByPrimaryKeySelective(order);
            }else {
                log.warn("支付宝回调签名验证失败，signVerified=false");
                throw new BaseException(StatusEnum.COMMON_EXCEPTION);
            }
        } catch (AlipayApiException e) {
          log.error("支付宝回调签名验证异常",e);
          throw new BaseException(StatusEnum.COMMON_EXCEPTION);
        }
    }
}
